package fragments;

import android.app.Fragment;

import dialogs.ProgressDialog;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.example.administrator.newxlmedical.R;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import beans.CabinetInfoBean;
import beans.CabinetInfoParentBean;
import beans.NewUserInfoBean;
import beans.SupplierRightsBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import utils.LoginRedCountUtils;
import utils.MD5;
import utils.ObjectSaveUtil;
import utils.ToastUtil;

/**
 * Created by Administrator on 2018/7/27.
 */

public class PasswordLoginFragment extends Fragment {

    Unbinder unbinder;
    @BindView(R.id.et_login_user)
    EditText etUser;
    @BindView(R.id.et_login_password)
    EditText etPassword;
    @BindView(R.id.tv_login_login)
    TextView tvLogin;

    //用于拼接所有的CabinetInfoId,方便sql语句(拼接终端下所有的CabinetInfoId)
    public StringBuilder sbCabinetInfoIds = new StringBuilder();
    //用来保存CabinetInfoId,和LogicNumber
    public Map<Integer, String> hashMap = new HashMap<>();
    //(拼接医药厂商可用的CabinetInfoId)
    public StringBuilder sbEnableLogicNumber = new StringBuilder();

    private ProgressDialog progressDialog;
    public SharedPreferences sharedPreferences;
    public int netWorkCount;
    public boolean isExitUser;//判断是否存在可用的用户
    @BindView(R.id.fl_empty)
    FrameLayout flEmpty;
    private boolean isFrist = true;
    private String cabinetInfoIds;
    //    private LoginDialog loginDialog;
    private NewUserInfoBean.DataBean bean;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HandlerConstant.FINISH_NETWORK:
                    Log.e("TAG", "handleMessage: netWorkCount");
                    netWorkCount++;
                    if (netWorkCount == 2) {
                        isFrist = true;
                        tvLogin.setClickable(true);
                        netWorkCount = 0;
                        if (isExitUser) {
                            String id;
                            if (bean.getRoleInfoId() != 1 && bean.getRoleInfoId() != 4) {
                                id = "0";
                            } else {
                                id = bean.getID() + "";
                            }
                            LoginRedCountUtils.getLoginDataCount(getActivity(), id, NetAddress.deptCode, true);
                        } else {
                            progressDialog.cancel();
                            sbCabinetInfoIds.delete(0, sbCabinetInfoIds.length());
                        }
                    }
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login_password, null);

        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.tv_login_login)
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tv_login_login) {
            if (isFrist) {
                progressDialog = new ProgressDialog(getActivity(), R.style.dialog, "正在登录，请稍候. . .");
                progressDialog.show();
                String userId = etUser.getText().toString();
                String password = etPassword.getText().toString();

                if (TextUtils.isEmpty(userId)) {
                    progressDialog.cancel();
                    ToastUtil.showToast(getActivity(), "请输入员工编号");
                    return;
                }

                if (TextUtils.isEmpty(password)) {
                    progressDialog.cancel();
                    ToastUtil.showToast(getActivity(), "请输入密码");
                    return;
                }
                tvLogin.setClickable(false);
                isFrist = false;
                userLogin("select * from UserInfo where UCode = '" + userId + "'");
                getCabinetInfoId();

            }
        }

    }

    //获取数据库cabinetInfo表的id,医疗厂商的权限会用到(此时查出的是此终端下面的所有的cabinetinfoid)
    public void getCabinetInfoId() {
        String sql = "select * from CabinetInfo where TerminalInfoID = " + NetAddress.terminalInfoId;
        GetRetrofit.getInstance().getCabinetInfoId(NetAddress.token, NetAddress.machineCode, sql)
                .subscribeOn(Schedulers.io()).groupBy(new Func1<List<CabinetInfoBean>, Boolean>() {
            @Override
            public Boolean call(List<CabinetInfoBean> cabinetInfoBeen) {
                return cabinetInfoBeen == null ? false : cabinetInfoBeen.size() > 0;
            }
        }).flatMap(new Func1<GroupedObservable<Boolean, List<CabinetInfoBean>>, Observable<CabinetInfoBean>>() {
            @Override
            public Observable<CabinetInfoBean> call(GroupedObservable<Boolean, List<CabinetInfoBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    return booleanListGroupedObservable.flatMap(new Func1<List<CabinetInfoBean>, Observable<CabinetInfoBean>>() {
                        @Override
                        public Observable<CabinetInfoBean> call(List<CabinetInfoBean> cabinetInfoBeen) {
                            CabinetInfoParentBean cabinetInfoParentBean = new CabinetInfoParentBean();
                            cabinetInfoParentBean.setCabinetInfoBeanList(cabinetInfoBeen);
                            ObjectSaveUtil.saveObject(getActivity(), cabinetInfoParentBean, Constants.CABINETINFO_PARENT_BEAN, Constants.CABINETINFO_PARENT_BEAN);
                            return Observable.from(cabinetInfoBeen).doOnNext(new Action1<CabinetInfoBean>() {
                                @Override
                                public void call(CabinetInfoBean cabinetInfoBean) {
                                    sbCabinetInfoIds.append(cabinetInfoBean.getID() + ",");
                                    hashMap.put(cabinetInfoBean.getID(), cabinetInfoBean.getLogicNumber());
                                }
                            }).last();
                        }
                    });
                } else {
                    Log.e("TAG", "call: getCabinetInfoId getkey null");
                    Message message = new Message();
                    message.what = HandlerConstant.FINISH_NETWORK;
                    handler.sendMessage(message);
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<CabinetInfoBean>() {
            @Override
            public void call(CabinetInfoBean cabinetInfoBean) {
                Log.e("TAG", "call: getCabinetInfoId getkey");
                cabinetInfoIds = sbCabinetInfoIds.deleteCharAt(sbCabinetInfoIds.length() - 1).toString();
                //查找供应商可用的cabinetinfoid
                getEnableCabinetInfoId(cabinetInfoIds);
                ObjectSaveUtil.saveObject(getActivity(), hashMap, Constants.CABINETINFO_LOGICNUMBER_HASHMAP, Constants.CABINETINFO_LOGICNUMBER_HASHMAP);

            }
        }, new MyAction1());
    }

    public void getEnableCabinetInfoId(String cabinetInfoIds) {
        String sql = "select * from SupplierRights where DeleteFlag = 0 and CabinetInfoId in (" + cabinetInfoIds + ")";
        GetRetrofit.getInstance().getSupplierRights(NetAddress.token, NetAddress.machineCode, sql)
                .subscribeOn(Schedulers.io()).groupBy(new Func1<List<SupplierRightsBean>, Boolean>() {
            @Override
            public Boolean call(List<SupplierRightsBean> supplierRightsBeen) {
                return supplierRightsBeen == null ? false : supplierRightsBeen.size() > 0;
            }
        }).flatMap(new Func1<GroupedObservable<Boolean, List<SupplierRightsBean>>, Observable<SupplierRightsBean>>() {
            @Override
            public Observable<SupplierRightsBean> call(GroupedObservable<Boolean, List<SupplierRightsBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    return booleanListGroupedObservable.flatMap(new Func1<List<SupplierRightsBean>, Observable<SupplierRightsBean>>() {
                        @Override
                        public Observable<SupplierRightsBean> call(List<SupplierRightsBean> supplierRightsBeen) {
                            return Observable.from(supplierRightsBeen).doOnNext(new Action1<SupplierRightsBean>() {
                                @Override
                                public void call(SupplierRightsBean supplierRightsBean) {
                                    sbEnableLogicNumber.append(hashMap.get(supplierRightsBean.getCabinetInfoId()) + ",");
                                }
                            }).last();
                        }
                    });
                } else {
                    Log.e("TAG", "call: getEnableCabinetInfoId null");
                    //没有查询到权限,应该将权限清空
                    Message message = new Message();
                    message.what = HandlerConstant.FINISH_NETWORK;
                    handler.sendMessage(message);

                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString(Constants.ENABLE_LOGICNUMBER, "");
                    edit.commit();
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<SupplierRightsBean>() {
            @Override
            public void call(SupplierRightsBean supplierRightsBean) {
                Log.e("TAG", "call: getEnableCabinetInfoId ");
                Message message = new Message();
                message.what = HandlerConstant.FINISH_NETWORK;
                handler.sendMessage(message);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString(Constants.ENABLE_LOGICNUMBER, sbEnableLogicNumber.toString());
                edit.commit();

            }
        }, new MyAction1());
    }

    //登录
    public void userLogin(String sql) {
        GetRetrofit.getInstance().getUserInfo2(NetAddress.token, NetAddress.machineCode, sql).subscribeOn(Schedulers.io())
                .groupBy(new Func1<NewUserInfoBean, Boolean>() {
                    @Override
                    public Boolean call(NewUserInfoBean newUserInfoBean) {
                        return newUserInfoBean == null ? false : newUserInfoBean.getData().size() > 0;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<GroupedObservable<Boolean, NewUserInfoBean>, Observable<NewUserInfoBean.DataBean>>() {
                    @Override
                    public Observable<NewUserInfoBean.DataBean> call(GroupedObservable<Boolean, NewUserInfoBean> booleanUserInfoBeanGroupedObservable) {
                        if (booleanUserInfoBeanGroupedObservable.getKey()) {
                            return booleanUserInfoBeanGroupedObservable.observeOn(Schedulers.io())
                                    .flatMap(new Func1<NewUserInfoBean, Observable<NewUserInfoBean.DataBean>>() {
                                        @Override
                                        public Observable<NewUserInfoBean.DataBean> call(NewUserInfoBean newUserInfoBean) {
                                            return Observable.from(newUserInfoBean.getData()).last();
                                        }
                                    });
                        } else {
                            Message message = new Message();
                            message.what = HandlerConstant.FINISH_NETWORK;
                            handler.sendMessage(message);
                            isExitUser = false;
                            ToastUtil.showToast(getActivity(), "用户不存在!");
                            return null;
                        }
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewUserInfoBean.DataBean>() {
                    @Override
                    public void call(NewUserInfoBean.DataBean dataBean) {
                        bean = dataBean;
                        if (dataBean.isEnable() && dataBean.getDelFlag() == 0) {
                            isExitUser = true;
                            ObjectSaveUtil.saveObject(getActivity(), dataBean, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);
                            String password = dataBean.getPassword();
                            Log.e("TAG", "call: " + password);
                            if (TextUtils.isEmpty(password)) {
                                ToastUtil.showToast(getActivity(), "您还没设置密码!");
                                isExitUser = false;
                            } else {
                                Log.e("TAG", "call: " + password + "  ==  " + MD5.md5(etPassword.getText().toString()));
                                if (!password.equals(MD5.md5(etPassword.getText().toString()))) {
                                    isExitUser = false;
                                    ToastUtil.showToast(getActivity(), "密码错误!");
                                }
                            }

                        } else {
                            isExitUser = false;
                            if (!dataBean.isEnable()) {
                                ToastUtil.showToast(getActivity(), "该用户已被禁用");
                            } else {
                                ToastUtil.showToast(getActivity(), "该用户已被删除");
                            }
                        }

                        Log.e("TAG", "call: login");
                        Message message = new Message();
                        message.what = HandlerConstant.FINISH_NETWORK;
                        handler.sendMessage(message);

                    }
                }, new MyAction1() {
                    @Override
                    public void call(Throwable throwable) {
                        super.call(throwable);
                        ToastUtil.showToast(getActivity(), "网络请求错误");
                        Message message = new Message();
                        message.what = HandlerConstant.FINISH_NETWORK;
                        handler.sendMessage(message);
                    }
                });
    }
}
